//
//  DiscoverListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/1/18.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "DiscoverListViewController.h"
#import "MinePageViewController.h"
#import "VoiceReadListViewController.h"
#import "DiscoverListItemCell.h"
#import "DiscoverListHeaderView.h"
#import "DiscoverListFooterView.h"
#import "LessonBannerModel.h"
#import "DiscoverListItemModel.h"
#import "UpdateVersionModel.h"
#import "HomePageActivityModel.h"
#import "AppDelegate.h"
#import "RPAppUpdateView.h"
#import "RPAppActivityView.h"
#import "CampusParamItemModel.h"
#import "CampusConfigModel.h"
#import "JHChineseSort.h"
#import "MineMessaeUnreadCountModel.h"
#import "HomePageMainListViewController.h"
#import "LessonUseageModel.h"
#import "DiscoverListItemCell.h"


@interface DiscoverListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong)UICollectionView *collectionView;
//@property (nonatomic,strong)UILabel *remindMessageLb;
@property (nonatomic,copy)NSArray *bannerArray;
@property (nonatomic,copy)NSArray *dataArray;
//@property (nonatomic,strong)DiscoverListFooterView *footerView;
@property (nonatomic,strong)DiscoverListHeaderView *headerView;
@property (nonatomic,assign)BOOL isShowFooter;
@property (nonatomic,assign)BOOL isHideUpdateView;
@property (nonatomic,strong)NSURLSessionTask *task;
@property (nonatomic,strong)NSURLSessionTask *task1;
@property (nonatomic,strong)UIImageView *coverImgView;
@property (nonatomic,strong)NSTimer *timer; /// 定时器用于刷新学习时间

@property (nonatomic,strong)UIImageView *mineImageView;
@property (nonatomic,strong)UIButton *mineBtn;


@property (nonatomic,strong)UIView *footerView;

@property (nonatomic,strong)UIImageView *backGroudImageView;

@end

@implementation DiscoverListViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.navigationController.navigationBar setBarTintColor:C21];
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//    self.navigationController.navigationBar.translucent = NO;
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = YES;
    [self.headerView adjustWhenControllerViewWillAppera];
    
    // 是否弹出在线升级和活动弹框
    [self loadAppUpdateSource];
    
    [self loadUnReadCountSource];

    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    [self registNote];
    
    [self loadBackGroundSource];
   
    [self showDataLoadState];
    
    [self loadDataSource];
    
    [self setCampusConfigInfo];
    
    // 刷新用户推送的设备token
    [self refreshDeviceToken];
    
    // 获取用户在线学习时间
    [self loadUserUseageSource];
    
    
}

- (void)setUI{
    
    self.isHideNavBar = YES;
    

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsZero;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing  = 0;
    layout.itemSize = CGSizeMake(kScreenW, kScreenH);
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,44, kScreenW, kScreenH) collectionViewLayout:layout];
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    

    [self.collectionView registerClass:[DiscoverListItemCell class] forCellWithReuseIdentifier:@"DiscoverListItemCell"];
    
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadBackGroundSource];
        [weakSelf loadDataSource];
    }];
    header.stateLabel.textColor = [UIColor whiteColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor whiteColor];
    header.loadingView.color = [UIColor whiteColor];
    
    self.collectionView.mj_header = header;

    self.backGroudImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"discover_bgImg_tag"]];
    self.backGroudImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.backGroudImageView.layer.masksToBounds = YES;
    self.backGroudImageView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    self.backGroudImageView.layer.zPosition = -1;
    [self.view addSubview:self.backGroudImageView];
    [self.backGroudImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.mineImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"discover_mine_tag"]];
    self.mineImageView.highlightedImage = [UIImage imageNamed:@"discover_mine_selected_tag"];
    [self.view addSubview:self.mineImageView];

    self.mineBtn = [[UIButton alloc]init];
    [self.mineBtn addTarget:self action:@selector(mineMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.mineBtn];
    
    [self.mineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50);
        make.right.equalTo(self.view).offset(-32);
    }];
    [self.mineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-16);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"localUrl"] != nil) {
        NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:@"localUrl"];
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        NSString* key = [manager cacheKeyForURL:[NSURL URLWithString:url]];
        SDImageCache* cache = [SDImageCache sharedImageCache];
        //此方法会先从memory中取。
        UIImage *image = [cache imageFromDiskCacheForKey:key];
        if (image != nil) {
            self.backGroudImageView.image = image;
        }
    }
    
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 300)];
    
    
    [self.view addSubview:self.footerView];
        
}

#pragma mark -action
- (void)mineMethod{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    MinePageViewController *mineVC = [[MinePageViewController alloc]init];
    [self.navigationController pushViewController:mineVC animated:YES];
}
- (void)buttonMethod:(UIButton *)btn{
    DiscoverListItemModel *itemModel = self.dataArray[btn.tag];
    [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:itemModel.url paramUrl:@""];
}

#pragma mark ---- 新增
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDeviceToken) name:@"updateRefreshToken" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeTimer) name:@"removeTimer" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadUserUseageSource) name:@"updateUserInfoUseage" object:nil];
}

- (void)applicationBecomeActive{
    if (self.isHideUpdateView && [[RPAppManager jsd_findVisibleViewController] isKindOfClass:[self class]]) {
        [self loadAppUpdateSource];
    }
}

- (void)loadBackGroundSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetBackGround];
    param[@"type"] = @1;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetBackGround) parames:param success:^(id responseObj) {
        if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
            NSString *url = responseObj[RESPONSE][@"url"];
            
            [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"localUrl"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            UIImage *old_image = [UIImage imageNamed:@"discover_bgImg_tag"];
            
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"localUrl"] != nil) {
                NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:@"localUrl"];
                SDWebImageManager *manager = [SDWebImageManager sharedManager];
                NSString* key = [manager cacheKeyForURL:[NSURL URLWithString:url]];
                SDImageCache* cache = [SDImageCache sharedImageCache];
                //此方法会先从memory中取。
                UIImage *image = [cache imageFromDiskCacheForKey:key];
                if (image != nil) {
                    old_image = image;
                }
            }
            [self.backGroudImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:old_image];
        }else{
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"localUrl"];
            UIImage *old_image = [UIImage imageNamed:@"discover_bgImg_tag"];
            self.backGroudImageView.image = old_image;
        }
    } failure:^(NSError *error) {
        
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"localUrl"];
        UIImage *old_image = [UIImage imageNamed:@"discover_bgImg_tag"];
        self.backGroudImageView.image = old_image;
        
    }];
}

- (void)loadUserUseageSource{

    if (![RPAppManager isLogin]) {
        return;
    }
    
    if (self.timer == nil) {
        [self autoUseageSource];
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserUsage];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserUsage) parames:param success:^(id responseObj) {
        LessonUseageModel *model = [LessonUseageModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        LessonUseageModel *oldModel = [LessonUseageModel getUseage];
        if (model == nil) {
            model = [[LessonUseageModel alloc]init];
        }
        if (model.lastUpdate.longValue < oldModel.lastUpdate.longValue) {
            model = oldModel;
        }
        if (model) {
            // 每次请求判断是否是同一天
            NSDate *pDate1 = [NSDate dateWithTimeIntervalSince1970:model.lastUpdate.longValue/1000];
            NSDate *pDate2 = [NSDate date];
            NSCalendar* calendar = [NSCalendar currentCalendar];
            unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
            NSDateComponents* comp1 = [calendar components:unitFlags fromDate:pDate1];
            NSDateComponents* comp2 = [calendar components:unitFlags fromDate:pDate2];
            if (!([comp1 day]==[comp2 day] &&
                [comp1 month] == [comp2 month] &&
                [comp1 year]  == [comp2 year])) {
                model.todayTime = @0;
            }
        }
        [model save];
        [self refreshUseage];
    } failure:^(id error) {

    }];
}

- (void)autoUseageSource{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(refreshUseage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

#pragma mark - 更新时间
- (void)refreshUseage{
    LessonUseageModel *model = [LessonUseageModel getUseage];
    if (![RPAppManager isLogin]) {
        return;
    }
    // 判断前天
    if ([[NSDate dateWithTimeIntervalSince1970:model.lastUpdate.longValue/1000] isBeforeYesterday]) {
        model.continuousTime = @0;
        [self updateUserLessonTimeByLessonUseageItem:model];
        return;
    }
    if (model.currentTodayTime.longLongValue == 0) {
        return;
    }
    [self updateUserLessonTimeByLessonUseageItem:model];
}


- (void)removeTimer{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)updateUserLessonTimeByLessonUseageItem:(LessonUseageModel *)item{
    NSTimeInterval time = (long long)[[NSDate date] timeIntervalSince1970] * 1000;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"todayTime"] = @(item.currentTodayTime.intValue + item.todayTime.intValue);
    param[@"md5"] = [RPAppManager md5StrWithApi:SaveUserUsage];
    param[@"lastUpdate"] = @(time);
    param[@"allTime"] = @(item.allTime.intValue + item.currentTodayTime.intValue);

    NSDate *pDate1 = [NSDate dateWithTimeIntervalSince1970:item.lastUpdate.longValue/1000];
    NSDate *pDate2 = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:pDate1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:pDate2];

    if ((!([comp1 day]==[comp2 day] &&
        [comp1 month] == [comp2 month] &&
        [comp1 year]  == [comp2 year])) && (item.currentTodayTime.intValue + item.todayTime.intValue)>0) {
        
        NSInteger continuousTime = item.continuousTime.intValue;
        continuousTime+=1;
        item.continuousTime = @(continuousTime);
    }

    param[@"continuousTime"] = item.continuousTime;

    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveUserUsage) parames:param success:^(id responseObj) {
        item.todayTime = @(item.currentTodayTime.intValue + item.todayTime.intValue);
        item.allTime = @(item.allTime.intValue + item.currentTodayTime.intValue);
        item.currentTodayTime = @0;
        item.lastUpdate = @([[NSDate date]timeIntervalSince1970] * 1000);
        // 保存本地
        [item save];
    } failure:^(id error) {

    }];
}

- (void)refreshDeviceToken{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"CLDeviceToken"] length] != 0) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"md5"] = [RPAppManager md5StrWithApi:UpdateDeviceToken];
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"deviceType"] = @2;
        param[@"deviceToken"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"CLDeviceToken"];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateDeviceToken) parames:param success:^(id responseObj) {
            
        } failure:^(id error) {
                        
        }];
    }
}


- (void)loadUnReadCountSource{
    
    if (![RPAppManager isLogin]) {
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:MessageTypeUnRead];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(MessageTypeUnRead) parames:param success:^(id responseObj) {
        NSArray *resultArray = [MineMessaeUnreadCountModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        
        __block BOOL isUnreadMessage = NO;
        __block NSInteger maxUnreadCount = 0;
     
        [resultArray enumerateObjectsUsingBlock:^(MineMessaeUnreadCountModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.messageUrNum.intValue > 0) {
                isUnreadMessage = YES;
            }
            maxUnreadCount += obj.messageUrNum.intValue;
        }];
        
        self.mineImageView.highlighted = maxUnreadCount > 0;
        
        
        [[NSUserDefaults standardUserDefaults]setObject:@(isUnreadMessage) forKey:@"messageReadStatus"];
        [[NSUserDefaults standardUserDefaults]setObject:@(maxUnreadCount) forKey:@"messageUnReadCount"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}


- (void)setCampusConfigInfo{
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetDictionaries) parames:nil success:^(id responseObj) {
        
        NSString *mainBundleDirectory = [[NSBundle mainBundle] bundlePath];
        NSString *path = [mainBundleDirectory stringByAppendingPathComponent:@"province.json"];
        NSURL *url = [NSURL fileURLWithPath:path];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *provinceArray = [CampusParamItemModel mj_objectArrayWithKeyValuesArray:dict[@"data"]];
        
        JHChineseSort *chineseSort = [[JHChineseSort alloc] init];
        
        NSMutableArray *cityList = [NSMutableArray array];
        
        NSArray *resultArray = [chineseSort chineseSortWithObjectArray:provinceArray];

        [cityList addObjectsFromArray:resultArray];
        
        CampusParamItemModel *cityItemModel = [CampusParamItemModel new];
        cityItemModel.name = @"-1";
        cityItemModel.value = @"不限";
        cityItemModel.isSelected = YES;
        [cityList insertObject:cityItemModel atIndex:0];
        
        NSArray *arr = [CampusConfigModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        [arr enumerateObjectsUsingBlock:^(CampusConfigModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSMutableArray *data = [NSMutableArray arrayWithArray:obj.paramList];
            CampusParamItemModel *itemModel = [CampusParamItemModel new];
            itemModel.name = @"-1";
            itemModel.value = @"不限";
            itemModel.isSelected = YES;
            [data insertObject:itemModel atIndex:0];
            obj.paramList = data;
            [obj saveWithKey:obj.code];
        }];
        CampusConfigModel *model = [[CampusConfigModel alloc]init];
        model.paramList = cityList;
        model.code = @"province";
        [model saveWithKey:@"province"];
    } failure:^(id error) {
            
    }];
}

- (void)loadAppUpdateSource{
        
    
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    if (appDelegate.appActivityStatus.intValue == 1) {
        return;
    }
    
    long time = [[[NSUserDefaults standardUserDefaults]objectForKey:@"updateVersionTime"] longValue];
    // 判断是否是今天提醒
    if ([[NSDate dateWithTimeIntervalSince1970:time]isToday]) {
        // 展示活动框
        [self loadActivitySource];
    }else{
        if (self.isHideUpdateView) {
            self.isHideUpdateView = NO;
        }
        __weak typeof(self)weakSelf = self;
        // 判断本地版本号
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        [[AFHTTPSessionManager manager] POST:@"http://itunes.apple.com/cn/lookup?id=1537342377" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *onlineVersion = [responseObject[@"results"] firstObject][@"version"];
            //获取更新版本信息
            NSString *message = [responseObject[@"results"] firstObject][@"releaseNotes"];
            NSComparisonResult reslut = [RPAppManager compareOnlineVersion:onlineVersion toVersion:app_Version];
            // 需要更新
            [self.task cancel];
            if (reslut == NSOrderedDescending) {
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                param[@"md5"] = [RPAppManager md5StrWithApi:CheckUpdate];
                param[@"appVersion"] = app_Version;
                param[@"deviceType"] = @1;
                self.task = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(CheckUpdate) parames:param success:^(id responseObj) {
                    if (![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[self class]]) {
                        return;
                    }
                    if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
                        UpdateVersionModel *versionModel = [UpdateVersionModel mj_objectWithKeyValues:responseObj[RESPONSE]];
                        versionModel.content = message;
                        RPAppUpdateView *updateView = [[RPAppUpdateView alloc]initWithUpdateVersionModel:versionModel completeBlock:^{
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/dd-up/id1537342377?mt=8"] options:@{} completionHandler:^(BOOL success) {}];
                            weakSelf.isHideUpdateView = YES;
                        } cancelBlock:^{
                            [weakSelf loadActivitySource];
                        }];
                        [updateView showInView:self.view];
                    }else{
                        [self loadActivitySource];
                    }
                } failure:^(id error) {
                    [self loadActivitySource];
                }];
            // 不需要更新的情况下
            }else{
                // 展示活动框
                [self loadActivitySource];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self loadActivitySource];
        }];
    }
}

- (void)loadActivitySource{
    [self.task1 cancel];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetEventGet];
    self.task1 = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetEventGet) parames:param success:^(id responseObj) {
    
        if (![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[self class]]) {
            return;
        }
        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        
        if (appDelegate.appActivityStatus.intValue == 1) {
            return;
        }
    
        appDelegate.appActivityStatus = @1;
        
        if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
            HomePageActivityModel *itemModel = [HomePageActivityModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            // 取出本地数据库对象
            RLMRealm *realm = [RLMRealm defaultRealm];
            //根据id取出本地对象
            RLMResults *results = [[HomePageActivityModel allObjects] objectsWhere:[NSString stringWithFormat:@"id == %ld",itemModel.id]];
            if (results.count > 0) {
                HomePageActivityModel *lastModel = results.firstObject;
                // 判断是否删除了banner
                if (itemModel.delete) {
                    [realm transactionWithBlock:^{
                        [realm deleteObjects:results];
                    }];
                }else{
                    // 每天展示一次
                    if (lastModel.fqcy != 1) {
                        // 判断是否是每次展示一次并且是否是今天展示过 || 判断每次都展示
                        if ((![[NSDate dateWithTimeIntervalSince1970:lastModel.showTime] isToday] && lastModel.fqcy == 2) || lastModel.fqcy == 3) {
                            itemModel.showTime = [NSDate date].timeIntervalSince1970;
                            [realm transactionWithBlock:^{
                                [realm addOrUpdateObject:itemModel];
                            }];
                            // 显示视图
                            RPAppActivityView *acView = [[RPAppActivityView alloc]initWithActivityItemModel:itemModel completeBlock:^{
            
                                if (itemModel.type == 2) {
                                    
                                }else{
                                    [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:itemModel.url paramUrl:@""];
                                }
                                
                            } cancelBlock:^{
                                
                            }];
                            [acView showInView:self.view];
                        }
                    }
                }
            }else{
                // 判断是否删除
                if (!itemModel.delete) {
                    // 当前展示时间
                    itemModel.showTime = [NSDate date].timeIntervalSince1970;
                    // 写入数据库
                    [realm transactionWithBlock:^{
                        [realm addOrUpdateObject:itemModel];
                    }];
                    RPAppActivityView *acView = [[RPAppActivityView alloc]initWithActivityItemModel:itemModel completeBlock:^{
                       
                        if (itemModel.type == 2) {
                            
                        }else{
                            [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:itemModel.url paramUrl:@""];
                        }
                    } cancelBlock:^{
                       
                    }];
                    [acView showInView:self.view];
                }
            }
        }
    } failure:^(id error) {
                
        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.appActivityStatus = @1;
    }];
}


- (void)loadDataSource{
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadItemListSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadBannerSource];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing]; 
        }
        
       
        
        [self hideDataLoadLoadState];
        
        
        [self.footerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        __block UIView *lastView = nil;
        
        NSInteger row = self.dataArray.count/4;
        NSInteger colum = self.dataArray.count%4;
        CGFloat itemH = 60;
        CGFloat paddingW = 64.0f;
        CGFloat marginW = 40.0f;
        CGFloat itemW = (kScreenW - paddingW * 2 - marginW * 3)/4;
        CGFloat marginH = 28;
      
        
        
        CGFloat count = row;
        if (colum != 0) {
            count +=1;
        }
        CGFloat maxH = itemH * count + (count - 1) * marginH;
        
        self.footerView.cl_height = maxH;
        self.footerView.cl_bottom = kScreenH - 100;
        
        
        [self.dataArray enumerateObjectsUsingBlock:^(DiscoverListItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSInteger colum = idx%4;
            UIView *view = [[UIView alloc]init];
            
            UIImageView *iconImgView = [[UIImageView alloc]init];
            iconImgView.contentMode = UIViewContentModeScaleAspectFill;
            iconImgView.layer.masksToBounds = YES;
            [self.footerView addSubview:iconImgView];
            
            [iconImgView sd_setImageWithURL:[NSURL URLWithString:obj.cover]];
            
            [self.footerView addSubview:view];
            
            UILabel *lb = [[UILabel alloc]init];
            lb.textColor = [UIColor whiteColor];
            lb.font = [UIFont boldSystemFontOfSize:12];
            [self.footerView addSubview:lb];
            
            lb.text = obj.programName;
            
            UIButton *btn = [[UIButton alloc]init];
            btn.tag = idx;
            [self.footerView addSubview:btn];
            
            [btn addTarget:self action:@selector(buttonMethod:) forControlEvents:UIControlEventTouchUpInside];
            
            
            if (lastView == nil) {
                [view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(self.footerView).offset(paddingW);
                    make.top.equalTo(self.footerView);
                    make.size.mas_equalTo(CGSizeMake(itemW, itemH));
                }];
            }else{
                if (colum == 0) {
                    [view mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(self.footerView).offset(paddingW);
                        make.top.equalTo(lastView.mas_bottom).offset(marginH);
                        make.size.mas_equalTo(CGSizeMake(itemW, itemH));
                    }];
                }else{
                    [view mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(lastView.mas_right).offset(marginW);
                        make.top.equalTo(lastView);
                        make.size.mas_equalTo(CGSizeMake(itemW, itemH));
                    }];
                }
            }
            lastView = view;
            
            [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.centerX.equalTo(view);
                make.size.mas_equalTo(CGSizeMake(32, 32));
            }];
            
            [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(view);
                make.bottom.equalTo(view);
            }];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.left.right.bottom.equalTo(view);
            }];
            
        }];

        
        
    });
}

- (void)loadItemListSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetProGramList];
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(9999);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetProGramList) parames:param success:^(id responseObj) {
        self.dataArray = [DiscoverListItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        dispatch_semaphore_signal(sema);
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadBannerSource{
//    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    param[@"scope"] = @3;
//    param[@"md5"] = [RPAppManager md5StrWithApi:GetBanner];
//    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetBanner) parames:param success:^(id responseObj) {
//        self.bannerArray = [LessonBannerModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
//        dispatch_semaphore_signal(sema);
//    } failure:^(id error) {
//        dispatch_semaphore_signal(sema);
//    }];
//    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DiscoverListItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DiscoverListItemCell" forIndexPath:indexPath];
    return cell;
}



- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}



@end
